#!/bin/bash

# LimeReader & LoimReader 快速部署脚本
# 简化版本，适合快速部署
# 使用方法: ./quick_deploy.sh [client_name] [version] [mode]

set -e

# 颜色定义
RED='\033[0;31m'
GREEN='\033[0;32m'
YELLOW='\033[1;33m'
BLUE='\033[0;34m'
NC='\033[0m'

# 默认参数
CLIENT_NAME=${1:-"LimeReader"}
VERSION=${2:-"auto"}
MODE=${3:-"local"}

# 配置映射
get_client_config() {
    case "$1" in
        "LimeReader")
            echo "limereader:LimeReader"
            ;;
        "LoimReader")
            echo "loimreader:LoimReader"
            ;;
        *)
            echo ""
            ;;
    esac
}

# 检查客户端参数
CLIENT_CONFIG_RESULT=$(get_client_config "$CLIENT_NAME")
if [[ -z "$CLIENT_CONFIG_RESULT" ]]; then
    echo -e "${RED}❌ 错误: 不支持的客户端 '$CLIENT_NAME'${NC}"
    echo -e "${YELLOW}支持的客户端: LimeReader, LoimReader${NC}"
    exit 1
fi

# 解析客户端配置
IFS=':' read -r CLIENT_DIR CLIENT_PREFIX <<< "$CLIENT_CONFIG_RESULT"

# 显示信息
echo -e "${BLUE}========================================${NC}"
echo -e "${BLUE}     $CLIENT_NAME 快速部署${NC}"
echo -e "${BLUE}========================================${NC}"
echo -e "${GREEN}客户端:${NC} $CLIENT_NAME"
echo -e "${GREEN}目录:${NC} $CLIENT_DIR"
echo -e "${GREEN}前缀:${NC} $CLIENT_PREFIX"
echo -e "${GREEN}模式:${NC} $MODE"
echo ""

# 自动获取版本号
if [ "$VERSION" == "auto" ]; then
    if [ -f "../build/version_info.json" ]; then
        VERSION=$(python3 -c "import json; print(json.load(open('../build/version_info.json'))['version'])" 2>/dev/null || echo "1.0.0")
        echo -e "${GREEN}✅ 从build/version_info.json检测到版本: $VERSION${NC}"
    elif [ -f "../app_version.h" ]; then
        # 尝试从宏定义中提取版本号
        VERSION=$(grep -A 5 -B 5 "APP_VERSION" ../app_version.h | grep -o 'APP_VERSION.*' | head -1 | sed 's/.*APP_VERSION.*"\(.*\)".*/\1/' | head -1)
        if [ -n "$VERSION" ] && [[ "$VERSION" != *"APP_VERSION"* ]]; then
            echo -e "${GREEN}✅ 从app_version.h检测到版本: $VERSION${NC}"
        else
            VERSION="2.7.1"  # 使用当前项目的默认版本
            echo -e "${YELLOW}⚠️  无法从app_version.h提取版本，使用默认版本: $VERSION${NC}"
        fi
    else
        VERSION="2.7.1"
        echo -e "${YELLOW}⚠️  无法自动检测版本，使用默认版本: $VERSION${NC}"
    fi
fi

# 创建目录
echo -e "${GREEN}📁 创建目录结构...${NC}"
mkdir -p "uploads/$CLIENT_DIR"
mkdir -p "dist/$CLIENT_DIR"/{windows,macos,linux}

# 生成版本文件
echo -e "${GREEN}📄 生成版本文件...${NC}"
VERSION_FILE="uploads/$CLIENT_DIR/version.json"

cat > "$VERSION_FILE" << EOF
{
  "latestVersion": "$VERSION",
  "releaseDate": "$(date -u +%Y-%m-%dT%H:%M:%SZ)",
  "releaseNotes": "$CLIENT_NAME 版本 $VERSION",
  "forceUpdate": false,
  "packages": {
    "windows": {
      "url": "${CLIENT_PREFIX}_v${VERSION}_Windows.zip",
      "size": "待计算",
      "hash": "待计算",
      "downloadUrl": "https://limereader-releases.oss-cn-hangzhou.aliyuncs.com/updates/$CLIENT_DIR/${CLIENT_PREFIX}_v${VERSION}_Windows.zip",
      "minSystemVersion": "Windows 10 或更高版本"
    },
    "macos": {
      "url": "${CLIENT_PREFIX}_v${VERSION}_macOS.dmg",
      "size": "待计算",
      "hash": "待计算",
      "downloadUrl": "https://limereader-releases.oss-cn-hangzhou.aliyuncs.com/updates/$CLIENT_DIR/${CLIENT_PREFIX}_v${VERSION}_macOS.dmg",
      "minSystemVersion": "macOS 10.15 或更高版本"
    },
    "linux": {
      "url": "${CLIENT_PREFIX}_v${VERSION}_Linux.tar.gz",
      "size": "待计算",
      "hash": "待计算",
      "downloadUrl": "https://limereader-releases.oss-cn-hangzhou.aliyuncs.com/updates/$CLIENT_DIR/${CLIENT_PREFIX}_v${VERSION}_Linux.tar.gz",
      "minSystemVersion": "Linux Kernel 4.15 或更高版本"
    }
  }
}
EOF

echo -e "${GREEN}✅ 版本文件已生成: $VERSION_FILE${NC}"

# 测试版本文件
echo -e "${GREEN}🧪 测试版本文件...${NC}"
if python3 -c "import json; json.load(open('$VERSION_FILE'))" 2>/dev/null; then
    echo -e "${GREEN}✅ 版本文件格式正确${NC}"
else
    echo -e "${RED}❌ 版本文件格式错误${NC}"
    exit 1
fi

# 显示后续步骤
echo ""
echo -e "${YELLOW}🚀 下一步操作:${NC}"
echo "1. 将构建好的应用文件放入: dist/$CLIENT_DIR/{windows,macos,linux}/"
echo "2. 运行完整部署脚本: ./universal_deploy.sh"
echo ""
echo -e "${YELLOW}🧪 测试命令:${NC}"
echo "curl https://limereader-releases.oss-cn-hangzhou.aliyuncs.com/updates/$CLIENT_DIR/version.json"
echo ""

# 如果是本地测试模式，尝试启动本地测试
if [ "$MODE" == "local" ]; then
    echo -e "${GREEN}🌐 启动本地测试服务器...${NC}"
    if command -v python3 &> /dev/null; then
        python3 -m http.server 8080 --directory uploads/$CLIENT_DIR &
        SERVER_PID=$!
        echo -e "${GREEN}✅ 测试服务器已启动 (PID: $SERVER_PID)${NC}"
        echo -e "${GREEN}📖 访问: http://localhost:8080/version.json${NC}"
        echo ""
        echo -e "${YELLOW}按任意键停止服务器...${NC}"
        read -n 1
        kill $SERVER_PID 2>/dev/null || true
        echo -e "${GREEN}✅ 测试服务器已停止${NC}"
    else
        echo -e "${YELLOW}⚠️  Python3未安装，无法启动测试服务器${NC}"
    fi
fi

echo -e "${GREEN}✨ 快速部署准备完成！${NC}"